Python编程-第七章-用户输入和while 循环
参考文章:
第 7 章 用户输入和while 循环
1. input() 工作原理
函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其赋给一个变量,以方便你使用。例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:
1.1. 一个简单的input 输入
name =input("Please enter your name:")
print(f"\nHellp,{name}!")
# 增加更多提示信息。
prompt = "If you tell us who you ar ,we can persionalize the message you seee."
prompt += "\nWhat is your first name? "
name =input(prompt)
print(f"\nHellp,{name}!")
在第二行中,运算符+= 在前面赋给变量prompt 的字符串末尾附加一个字符串。
Warning
注意: intput() 函数默认解释为字符串。所以需要指定获取的类型。
1.2. 将字符串转换为数字
age = input("How old are you? ")
age = int(age)
if age >= 18:
print(f"True")
else:
print(f"Fasle")
# 判断是否能够做过山车
height = input("How tall are you ,in cm?")
height = int(height)
if height >= 48:
print("\n You're tall engough to ride!")
else:
print(f"\n You'll be able to ride when you're a little older.")
2. 求模(求余数)
# 求偶数还是奇数
number = input("Enter a number ,and I'll tell you if it's even or odd:")
number = int (number)
if number % 2 == 0:
print(f"\nThe numbder {number} is even.")
else:
print(f"\nThe number {number} is odd.")
2.1. 练习题
练习7-1:汽车租赁 编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,下面是一个例子。
car = input("你想要什么汽车?")
print(f"\nLet me see if I can find you a {car}.")
练习7-2:餐馆订位 编写一个程序,询问用户有多少人用餐。如果超过8位,就打印一条消息,指出没有空桌;否则指出有空桌
user_number = input("有多少用户进行用餐?")
user_number = int(user_number)
if user_number > 8:
print(f"没有空桌。")
else:
print(f"有空桌。")
练习7-3:10的整数倍 让用户输入一个数,并指出该数是否是10的整数倍。
user_number = input("让我来告诉你此数是否是10 的整数倍。")
user_number = int(user_number)
if user_number % 10 == 0:
print(f"是10 的整数倍。")
else:
print(f"不是10 的整数倍。")
3. while 循环简介
for 循环用于针对集合中的每个元素都执行一个代码块,而while 循环则不断运行,直到指定的条件不满足为止
current_number = 1
while current_number <=5:
print(current_number)
current_number +=1
3.1. 用户输入控制循环条件
prompt = "\nTel me sometion, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message =""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# 使用标记进行循环条件的判断。
prompt = "\nTel me sometion, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
acitive = True
while acitive:
message = input(prompt)
if message == 'quit':
acitive = False
else:
print(message)
# break 控制循环
while True:
city = input(prompt)
if city== 'quit':
break
else:
print(city)
# 使用continue 控制循环。打印无法被 2 整除的数字。
current_number = 0
while current_number < 10:
current_number +=1
if current_number % 2 == 0:
continue
print(current_number)
3.2. 练习题
练习7-4:比萨配料 编写一个循环,提示用户输入一系列比萨配料,并在用户输入'quit' 时结束循环。每当用户输入一种配料后,都打印一条消息,指出我们会在比萨中添加这种配料
pizza=[]
acitive = True
prompt = "\nPlease add the required ingredients:"
prompt += "\nplease enter quit exit the program."
while acitive:
burden=input(prompt)
if burden == 'quit':
acitive = False
else:
pizza.append(burden)
print(pizza)
2334
练习7-5:电影票 有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众收费10美元;超过12岁的观众收费15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
while True:
age = input("Please enter your age:")
age = int(age)
if age < 3:
price = 0
print(f"your fare is {price}")
elif age >=3 and age <=12:
price = 10
print(f"your fare is {price}")
elif age >12 :
price = 20
print(f"your fare is {price}")
elif age == 'quit':
break
4. 使用while 处理列表和字典
Warning
需要修改用while ,需要打印用for 语句。
4.1. 在列表中移动元素
UNAUTHENTICATED_USER = ['alice','brian','candace']
confirmed_users = []
while UNAUTHENTICATED_USER:
current_user = UNAUTHENTICATED_USER.pop()
# pop is to remove the element from the end of the list each time and assign it to the current_user variable.
print(f"Verifying user:{current_user.title()}")
confirmed_users.append(current_user)
# show all authenticated users
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
4.2. 删除为特定值的所有列表元素
pets = ['dog','cat','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
4.3. 使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
# Prompt for the respondent's name
name=input("\nWhat is your name? ")
response =input("Which mountain would you like to climb someday? ")
# Store the answer in a dictionary.
responses[name] = response
# See if anyone else wants to take the survey.
repeat = input("Would you like to let another persion respond? (yes/no)")
if repeat == 'no':
polling_active = False
# The survey is over and the results are displayed
print("\n--- Poll Results ---")
for name,response in responses.items():
print(f"{name} would like to climb {response}.")
4.4. 练习题
sandwich_orders =['alice','mawe','tage']
finished_sandwich =[]
while sandwich_orders:
current_sanwich = sandwich_orders.pop()
finished_sandwich.append(current_sanwich)
print(f"I made you {current_sanwich}.")
print(f"I finnished all sandwich{finished_sandwich}")
sandwich_orders =['alice','mawe','pastrami','lili','pastrami','mato','pastrami']
print("All pastrami is sold out!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
练习7-10:梦想的度假胜地 编写一个程序,调查用户梦想的度假胜地。使用类似于下面的提示,并编写一个打印调查结果的代码块。
responses = {}
polling_active = True
while polling_active:
# Prompt for the respondent's name
name=input("\nWhat is your name? ")
response =input("Your dream vacation spot?")
# Store the answer in a dictionary.
responses[name] = response
# See if anyone else wants to take the survey.
repeat = input("Would you like to let another vaction? (yes/no)")
if repeat == 'no':
polling_active = False
# The survey is over and the results are displayed
print("\n--- Poll Results ---")
for name,response in responses.items():
print(f"{name} would like to vaction {response}.")